package mvc.handlers;

import facade.DocenteFacadeRemote;
import facade.SegreteriaFacadeRemote;
import facade.StudenteFacadeRemote;
import util.InterfaceUtente;

import mvc.framework.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * Handler per gestire l'azione di visualizzazione del profilo di un utente
 * 
 * @author Grillo
 */
public class ShowProfileHandler extends AbsRequestHandler {

    //costanti di errore
    public final static int ERR_MISSED_USER = 1;

    private final static String ACTION_NAME = "showProfile";

    public ShowProfileHandler(DialogHandler dHandler) {
        super(dHandler);

        //Aggiungo la descrizione degli errori
        errors.add("L'utente cercato non è stato trovato");
    }

    public String getActionName() {
        return ACTION_NAME;
    }

    public void setNextPage() {
        nextPage = "/views/profile.jsp";
    }
    
    public int validate() {
        //controllo che i campi sono impostati
        String user = dialogHandler.getParameter("user");
        if(user!=null && !user.equals(""))
            return SUCCESS;
        else
            return ERR_MISSED_USER;
    }

    public int execute() {
        String tipo = "";
        Integer user = 0;
        DocenteFacadeRemote docenteFacade = null;
        SegreteriaFacadeRemote segreteriaFacade = null;
        StudenteFacadeRemote studenteFacade = null;

        try {
            tipo = dialogHandler.getParameter("user").substring(0,2);
            user = Integer.parseInt(dialogHandler.getParameter("user").substring(2));
        } catch(Exception e) {}
       
        //Bind agli EJB
        try {
            Context c = new InitialContext();
            docenteFacade = (DocenteFacadeRemote) c.lookup("facade.DocenteFacadeRemote");
            segreteriaFacade = (SegreteriaFacadeRemote) c.lookup("facade.SegreteriaFacadeRemote");
            studenteFacade = (StudenteFacadeRemote) c.lookup("facade.StudenteFacadeRemote");
        } catch (NamingException ne) {}

        InterfaceUtente obj = null;
        if(tipo.equalsIgnoreCase("st"))
            obj = studenteFacade.findByMatricola(user);
        if(tipo.equalsIgnoreCase("do"))
            obj = docenteFacade.findByMatricola(user);
        if(tipo.equalsIgnoreCase("se"))
            obj = segreteriaFacade.findByMatricola(user);
        if(obj == null)
            return ERR_MISSED_USER;

        SessionManager.setAttribute(dialogHandler.getSession(), "userBean", obj);
        return SUCCESS;
    }

    @Override
    public IRequestHandler clone(DialogHandler dHandler) throws CloneNotSupportedException {
        return new ShowProfileHandler(dHandler);
    } 
}